package com.ukao.steward.ui.valetRunners.sendLetter;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.DontSendAdapter;
import com.ukao.steward.adapter.DontTakerAdapter;
import com.ukao.steward.base.IAdapter;
import com.ukao.steward.base.IPage;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.base.PageWrapper;
import com.ukao.steward.bean.WaitingOrderBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.eventbus.ShoppEvent;
import com.ukao.steward.listener.OnItemChildClickListener;
import com.ukao.steward.pesenter.valetRunners.DontTakePesenter;
import com.ukao.steward.ui.valetRunners.takeLetter.TakeLetterTabFragment;
import com.ukao.steward.ui.valetRunners.waitingOrder.OrderdetailFragment;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.DontTakeView;
import com.ukao.steward.widget.ClearEditText;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/*
* 送件
 */
public class DontTakeFragment extends MvpFragment<DontTakePesenter> implements DontTakeView {
    @BindView(R.id.lrecycler_view)
    MyLRecyclerView lrecyclerView;
    Unbinder unbinder;
    @BindView(R.id.sweep_image)
    ImageView sweepImage;
    @BindView(R.id.edit_text)
    ClearEditText editText;
    @BindView(R.id.sure_btn)
    StateButton sureBtn;
    @BindView(R.id.search_layout)
    LinearLayout searchLayout;
    private int mColumnCount;
    private DontTakerAdapter mDontTakerAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private List<WaitingOrderBean.ListBean> mData;
    private PageWrapper mPageWrapper;
    private DontSendAdapter mDontSendAdapter;
    private View view;
    private TakeLetterTabFragment mTakeLetterTabFragment;
    private int total;
    private View mEmptyView;
    public String storeId = "";

    public static DontTakeFragment newInstance(int columnCount) {
        DontTakeFragment fragment = new DontTakeFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_PARAM1);
        }
    }

    @Override
    protected DontTakePesenter createPresenter() {
        return new DontTakePesenter(this);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        lrecyclerView.forceToRefresh();  //调用刷新
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_enter_factorys, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
    }


    @Override
    protected void initView() {
        //取件
        editText.requestFocus();
        searchLayout.setVisibility(mColumnCount == 1 ? View.VISIBLE : View.GONE);
        mEmptyView = view.findViewById(R.id.empty_view);
        //lrecyclerView.setEmptyView(mEmptyView);//设置在setAdapter之前才能生效
        mData = new ArrayList<>();
        initLinearRecyclerView(lrecyclerView);
        initAdapter();
        IPage page = new IPage() {


            @Override
            public void load(int geIndex, int pageSize) {
                mvpPresenter.requestReceiving(geIndex, pageSize, mColumnCount, storeId);

            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);


    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            mEmptyView.setVisibility(CheckUtils.isEmpty(data) ? View.VISIBLE : View.GONE);
            cleanData();
            setNewData(data, isNextLoad);
            mLRecyclerViewAdapter.notifyDataSetChanged();
        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {

            setLoadMoreData(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            if (!isNextLoad) lrecyclerView.setNoMore(!isNextLoad);
        }
    };


    @Override
    protected void initListener() {
        super.initListener();
        lrecyclerView.setOnRefreshListener(mOnRefreshListener);
        lrecyclerView.setOnLoadMoreListener(mOnLoadMoreListener);
        setItemChildListener();
        mLRecyclerViewAdapter.setOnItemClickListener(mOnItemClickListener);
        editText.setOnEditorActionListener(mOnEditorActionListener);

    }

    private TextView.OnEditorActionListener mOnEditorActionListener = (v, actionId, event) -> {

        if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
            String strEditText = getText(editText);
            if (!CheckUtils.isEmpty(strEditText)) {
                mvpPresenter.scancode(strEditText);
                KeyBoardUtil.hideInputmethod(editText);
                setFoucus();
            }

        }

        return false;
    };

    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            String orderid = "";
            switch (mColumnCount) {
                case 1:/*未取*/
                    orderid = mDontTakerAdapter.getCount(position).getId();
                    break;
                case 2:/*未送*/
                    orderid = mDontSendAdapter.getCount(position).getId();
                    break;
                case 3:/*完成*/
                    orderid = mDontSendAdapter.getCount(position).getId();
                    break;

            }
            if (getParentFragment() instanceof TakeLetterTabFragment) {
                mTakeLetterTabFragment = ((TakeLetterTabFragment) getParentFragment());
                OrderdetailFragment mOrderdetail = OrderdetailFragment.createBuilder()
                        .orderId(orderid)
                        .isEndledSign(mColumnCount == 2)
                        .build();

                mTakeLetterTabFragment.start(mOrderdetail);
            }
        }
    };

    public void setItemChildListener() {
        switch (mColumnCount) {
            case 1:/*未取*/
                mDontTakerAdapter.setOnItemChildClickListener(mOnItemChildClick);
                break;
            case 2:/*未送*/
                mDontSendAdapter.setOnItemChildClickListener(mOnItemChildClick);
                break;

        }
    }

    private OnItemChildClickListener mOnItemChildClick = new OnItemChildClickListener() {


        public WaitingOrderBean.ListBean mTakeItem;
        @Override
        public void onChildItemClick(int id, int pos, Object o) {
            mTakeItem = (WaitingOrderBean.ListBean) o;
            switch (id) {
                case R.id.take_btn:/*取件 未送*/
                    mvpPresenter.receivingSend(mTakeItem);
                    break;
                case R.id.signIn_btn:/*未送签收*/
                    mvpPresenter.signParcel(mTakeItem);
                    break;
            }

        }
    };


    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            cleanData();
            mLRecyclerViewAdapter.notifyDataSetChanged();
            mPageWrapper.loadPage(true);
        }
    };
    private OnLoadMoreListener mOnLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            mPageWrapper.loadPage(false);
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void initAdapter() {
        switch (mColumnCount) {
            case 1:
                mDontTakerAdapter = new DontTakerAdapter(_mActivity, mData);
                mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDontTakerAdapter);
                break;
            case 2:
                mDontSendAdapter = new DontSendAdapter(_mActivity, mData);
                mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDontSendAdapter);
                break;
            case 3:
                mDontSendAdapter = new DontSendAdapter(_mActivity, mData);
                mDontSendAdapter.setFinishEnter(true);
                mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDontSendAdapter);

                break;
        }
        lrecyclerView.setAdapter(mLRecyclerViewAdapter);
    }

    public void cleanData() {


        switch (mColumnCount) {
            case 1:/*未取*/
                mDontTakerAdapter.getDataList().clear();
                break;
            case 3:
            case 2:/*未送*/
                mDontSendAdapter.getDataList().clear();

                break;
        }
    }

    public void setNewData(List data, boolean isNextLoad) {
        switch (mColumnCount) {
            case 1:/*未取*/
                mDontTakerAdapter.setDataList(data);
                lrecyclerView.setLoadMoreEnabled(isNextLoad);
                break;
            case 3:
            case 2:/*未送*/
                mDontSendAdapter.setDataList(data);
                lrecyclerView.setLoadMoreEnabled(isNextLoad);
                break;

        }
    }

    public void setLoadMoreData(List data) {
        switch (mColumnCount) {
            case 1:/*未取*/
                mDontTakerAdapter.addAll(data);
                break;
            case 3:
            case 2:/*未送*/
                mDontSendAdapter.addAll(data);
                break;

        }
    }

    public void setStoreId(String storeId) {
        this.storeId = storeId;
        lrecyclerView.forceToRefresh();

    }

    @Override
    public void receiveNoTakeSucceed(WaitingOrderBean mWaitingOrderBean) {
        if (getParentFragment() instanceof TakeLetterTabFragment) {
            mTakeLetterTabFragment = ((TakeLetterTabFragment) getParentFragment());
            total = mWaitingOrderBean.getTotal();
            switch (mColumnCount) {
                case 1:
                    mTakeLetterTabFragment.updataSendNotTake(mWaitingOrderBean.getTotal());
                    break;
                case 2:
                    mTakeLetterTabFragment.updataSendNotSend(mWaitingOrderBean.getTotal());
                    break;
            }
        }
        mPageWrapper.addDataSource(mWaitingOrderBean.getList(), mWaitingOrderBean.getPages());

    }

    @Override
    public void loadfinish() {
        lrecyclerView.refreshFinish();
    }

    @Override
    public void receivingSucceed(WaitingOrderBean.ListBean mListBean, String msg) {
        T.show(msg);
        total = total - 1;
        switch (mColumnCount) {
            case 1:/*未取*/
                if (!CheckUtils.isNull(mTakeLetterTabFragment)) {
                    mTakeLetterTabFragment.updataSendNotTake(total);
                }
                mDontTakerAdapter.getDataList().remove(mListBean);
                mDontTakerAdapter.notifyDataSetChanged();
                break;
            case 2:/*未交*/
                if (!CheckUtils.isNull(mTakeLetterTabFragment)) {
                    mTakeLetterTabFragment.updataSendNotSend(total);
                }
                mDontSendAdapter.getDataList().remove(mListBean);
                mDontSendAdapter.notifyDataSetChanged();
                break;

        }

    }

    @Override
    public void takeSuccerd() {
        lrecyclerView.forceToRefresh();
        setFoucus();
    }

    @OnClick({R.id.sweep_image, R.id.sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sweep_image:
                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent, Constant.REQUEST_CODE);
                break;
            case R.id.sure_btn:
                scancode();

                break;
        }
    }

    void scancode() {
        String strEditText = getText(editText);
        if (!CheckUtils.isEmpty(strEditText)) {
            mvpPresenter.scancode(strEditText);
            KeyBoardUtil.hideInputmethod(editText);

        }
    }

    void setFoucus() {
        editText.setText("");
        editText.requestFocus();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == _mActivity.RESULT_OK) {

            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String code = data.getStringExtra(Constant.ARG_PARAM1);
                    editText.setText(code);
                    scancode();
                    break;
            }
        }

    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    /**
     * 接收到推送
     */
    @Subscribe
    public void onEvent(ShoppEvent event) {
        switch (event.getMessage()) {
            case STORE:
               if (  event.getData()  instanceof String);
                storeId=(String)event.getData();
                break;
        }
    }
}
